<script setup lang="ts">
import type { CalendarList, DateList, Room } from './interface';

import { computed, createVNode, ref, watch } from 'vue';

import {
  MdiDownBold,
  MdiLeftBold,
  MdiMeals2,
  MdiRightBold,
  MdiUpBold,
} from '@vben/icons';

import { ExclamationCircleFilled } from '@ant-design/icons-vue';
import { Divider, Modal, Spin, Switch, Tooltip } from 'ant-design-vue';
import dayjs from 'dayjs';

import { updateRoomStatus } from '#/api';

const props = defineProps({
  formData: {
    type: Object,
    default: () => ({}),
  },
  roomList: {
    type: Array as () => Room[],
    default: () => [],
  },
  list: {
    type: Array as () => CalendarList[],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(['changlePage', 'roomSet', 'priceSet', 'upList']);

// 定义一个 ref 来存储选中的天数
const daysCount = ref(0);

// 定义一个 ref 来存储开始日期
const startDate = ref<dayjs.Dayjs>(dayjs().startOf('day'));

// 监听 props.formData.selectDate 的变化
watch(
  () => props.formData.selectDate,
  (newSelectDate) => {
    const [start, end] = newSelectDate;
    daysCount.value =
      start && end ? dayjs(end).diff(dayjs(start), 'day') + 1 : 0;
    startDate.value = start || dayjs().startOf('day');
  },
  { immediate: true },
);

// 计算十天前的日期
const tenDaysAgo = dayjs().subtract(13, 'day').startOf('day');

// 定义一个 computed 来判断是否超过十天前
const isToday = computed(() => {
  return startDate.value.isBefore(tenDaysAgo);
});

// 星期枚举
const weekDays = [
  '星期日',
  '星期一',
  '星期二',
  '星期三',
  '星期四',
  '星期五',
  '星期六',
];

// 是否收起全部
const isCollapse = ref(false);

// 定义一个 ref 来存储滚动距离
const scrollX = ref(0);

// 被收起的房型ID
const collapseIds = ref<(number | string)[]>([]);

// 点击收起列表或者展开列表
const handleCollapse = (id: number | string) => {
  const index = collapseIds.value.indexOf(id);
  if (index === -1) {
    collapseIds.value.push(id);
  } else {
    collapseIds.value.splice(index, 1);
  }
  isCollapse.value = collapseIds.value.length === props.roomList.length;
};
// 全部展开收起事件
const handleCollapseAll = () => {
  isCollapse.value = !isCollapse.value;
  collapseIds.value = isCollapse.value
    ? props.roomList.map((item) => item.id)
    : [];
};

// 滚动事件处理函数
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  scrollX.value = target.scrollLeft;
};
// 日期翻页
const handlePage = (type: string) => {
  if (type === 'reduce' && isToday.value) {
    return;
  }
  emit('changlePage', type);
};

// 判断日期是否小于今天
const getCursorState = (date: string) => {
  return dayjs(date, 'YYYY-MM-DD').isBefore(dayjs().startOf('day'))
    ? 'cursor-not-allowed'
    : 'cursor-pointer';
};
// 是否可以点击
const getDateState = (date: string) => {
  return !!dayjs(date, 'YYYY-MM-DD').isBefore(dayjs().startOf('day'));
};

// 点击房量打开弹窗设置房间信息
const handleRoomSet = (data: DateList) => {
  if (getDateState(data.saleDate)) {
    return;
  }
  emit('roomSet', data);
};

// 打开房价设置
const handleRoomPrice = (data: DateList) => {
  if (getDateState(data.saleDate)) {
    return;
  }
  emit('priceSet', data);
};

// 获取房型列表
const getList = (id: number | string) => {
  return props.list?.find((i) => i.roomId === id)?.list || [];
};

// 开关loading
const loadSwitch = ref<{ [key: string]: boolean }>({});

// 开关房
const roomSwitch = async (data: DateList) => {
  try {
    await updateRoomStatus({
      endTime: data.saleDate || '',
      roomStatus: data.roomStatus === 1 ? 2 : 1,
      roomTypeId: data.roomId || '',
      startTime: data.saleDate || '',
    });
    loadSwitch.value = {};
    emit('upList');
  } catch (error) {
    console.error('状态切换失败：', error);
  }
};

// 点击改变房间状态
const handleRoomState = (data: DateList) => {
  if (getDateState(data.saleDate)) {
    return;
  }
  loadSwitch.value = { [data.saleDate + data.roomId]: true };
  // 先判断是开房状态还是关闭状态 如果是关闭状态就直接调用开启接口，开启状态就走提示弹窗然后再关闭房型
  if (data.roomStatus === 1) {
    Modal.confirm({
      title: '关房可能影响收益，请确认是否关房。',
      icon: createVNode(ExclamationCircleFilled),
      onOk: async () => {
        await roomSwitch(data);
      },
      onCancel: () => {
        loadSwitch.value = {};
      },
    });
  } else {
    roomSwitch(data);
  }
};
</script>

<template>
  <div class="relative w-full flex-auto overflow-hidden pr-4">
    <div
      v-if="loading"
      class="z-100 absolute left-0 top-0 flex h-full w-full flex-auto items-center justify-center bg-white"
    >
      <Spin size="large" />
    </div>
    <!-- 左右切换按钮 -->
    <div
      :class="[isToday ? 'cursor-not-allowed opacity-20' : '']"
      class="card-box leftBut absolute left-[262px] top-0 z-[15] flex h-[60px] w-[30px] cursor-pointer items-center justify-center rounded-none border-none text-base"
      @click="handlePage('reduce')"
    >
      <MdiLeftBold />
    </div>
    <div
      class="card-box rightBut absolute right-7 top-0 z-[15] flex h-[60px] w-[30px] cursor-pointer items-center justify-center rounded-none border-none text-base"
      @click="handlePage('add')"
    >
      <MdiRightBold />
    </div>
    <div
      id="room"
      class="room relative h-full w-full overflow-auto"
      @scroll="handleScroll"
    >
      <!-- 房型表单头部 -->
      <div
        class="room-head card-box sticky top-0 z-[12] flex rounded-none border-none pl-[292px]"
      >
        <!-- 左侧 -->
        <div
          :style="{ left: `${scrollX}px` }"
          class="card-box absolute top-0 z-[12] flex h-full w-[292px] items-center rounded-none border-x-0 border-b border-t-0 pl-5"
        >
          <div
            class="hover:text-primary no-select flex h-full cursor-pointer items-center text-base"
            @click="handleCollapseAll"
          >
            <span class="mr-2">{{ isCollapse ? '展开全部' : '收起全部' }}</span>
            <MdiDownBold v-if="isCollapse" />
            <MdiUpBold v-else />
          </div>
        </div>
        <div class="pr-6">
          <ul class="card-box flex rounded-none border-x-0 border-b border-t-0">
            <li
              v-for="index in daysCount"
              :key="index"
              class="flex h-[60px] w-[82px] flex-col items-center justify-center text-center"
            >
              <p
                :class="[
                  [0, 6].includes(
                    dayjs(startDate)
                      .add(index - 1, 'day')
                      .day(),
                  )
                    ? 'font-bold'
                    : 'opacity-80',
                ]"
              >
                {{
                  weekDays[
                    dayjs(startDate)
                      .add(index - 1, 'day')
                      .day()
                  ]
                }}
              </p>
              <p class="mt-0.5">
                {{
                  dayjs(startDate)
                    .add(index - 1, 'day')
                    .format('MM-DD')
                }}
              </p>
            </li>
          </ul>
        </div>
      </div>
      <!-- 房型表单区域 -->
      <div v-for="item in roomList" :key="item.id" class="room-body">
        <div class="room-list-top relative flex pl-[292px]">
          <div
            :style="{ left: `${scrollX}px` }"
            class="card-box absolute top-0 z-[10] flex h-full w-[292px] rounded-none border-none"
          >
            <div
              class="room-info flex h-full w-full cursor-pointer items-center border-b bg-black bg-opacity-5 pl-4"
              @click="handleCollapse(item.id)"
            >
              <div class="no-select flex flex-auto flex-col justify-center">
                <p class="font-bold">{{ item.nameZh || '' }}</p>
                <p class="mt-0.5">共{{ item.roomNum || '' }}间</p>
              </div>
              <div class="absolute right-4 text-base">
                <MdiDownBold v-if="collapseIds.includes(item.id)" />
                <MdiUpBold v-else />
              </div>
            </div>
          </div>
          <!-- v-for="room in getList(item.id)" :key="room.saleDate" -->
          <ul class="flex border-b bg-black bg-opacity-5">
            <li
              v-for="room in getList(item.id)"
              :key="room.saleDate"
              class="flex min-h-[64px] w-[82px] flex-col items-center pt-3 text-center"
            >
              <Tooltip>
                <template v-if="!getDateState(room.saleDate)" #title>
                  {{ room.roomStatus === 1 ? '点击关房' : '点击开房' }}
                </template>
                <Switch
                  :checked="room.roomStatus === 1"
                  :disabled="getDateState(room.saleDate)"
                  :loading="loadSwitch[room.saleDate + room.roomId]"
                  size="small"
                  @click="handleRoomState(room)"
                />
              </Tooltip>
              <p v-if="room.saleNum" class="mt-1 opacity-80">
                已售{{ room.saleNum }}
              </p>
            </li>
          </ul>
        </div>
        <div
          v-if="!collapseIds.includes(item.id)"
          class="relative flex pl-[292px] pr-6"
        >
          <div
            :style="{ left: `${scrollX}px` }"
            class="card-box absolute top-0 z-[10] flex h-full w-[292px] rounded-none border-x-0 border-b border-t-0 pl-4"
          >
            <div class="flex flex-auto flex-col py-2 pr-2">
              <p>
                {{ item.nameZh || '' }}
                <span v-if="item.breakfastCount">
                  ({{ item.breakfastCount }}份早餐)
                </span>
              </p>
            </div>
            <div
              class="flex h-full w-[50px] flex-col justify-between border-r opacity-60"
            >
              <div v-if="formData.showRoomInfo" class="pb-2 pt-3">
                <p class="mb-1 scale-[0.9] py-0.5">房态</p>
                <p class="scale-[0.9]">房量</p>
              </div>
              <div v-if="formData.showPrice" class="py-2">
                <p class="scale-[0.9]">卖价</p>
                <p class="scale-[0.9]">餐食</p>
              </div>
            </div>
          </div>
          <ul class="flex border-b">
            <li
              v-for="room in getList(item.id)"
              :key="room.roomId"
              :class="[
                room.roomStatus === 2 || !room.quotaCount
                  ? 'bg-red-300/10'
                  : '',
              ]"
              class="min-h-[64px] w-[82px] border-r text-center"
            >
              <div v-if="formData.showRoomInfo" class="flex flex-col pt-3">
                <div
                  :class="[
                    room.roomStatus === 2 || !room.quotaCount
                      ? 'bg-red-500 text-white'
                      : 'bg-main text-primary',
                    getCursorState(room.saleDate),
                  ]"
                  class="py-0.5"
                  @click="handleRoomState(room)"
                >
                  {{
                    Number(room.quotaCount) <= 0 && room.saleMode === 1
                      ? '售完'
                      : room.roomStatus === 1
                        ? '已开房'
                        : '已关房'
                  }}
                </div>
                <div
                  :class="[getCursorState(room.saleDate)]"
                  class="flex-auto py-1.5 hover:bg-black hover:bg-opacity-5"
                  @click="handleRoomSet(room)"
                >
                  <span
                    :class="[false ? 'text-primary' : '']"
                    class="font-bold"
                  >
                    {{ room.saleMode === 1 ? '限量' : 'FS' }}
                  </span>
                  <span class="ml-2">剩{{ room.quotaCount || 0 }}</span>
                </div>
              </div>
              <Divider
                v-if="formData.showRoomInfo && formData.showPrice"
                class="m-0"
              />
              <div
                v-if="formData.showPrice"
                :class="[getCursorState(room.saleDate)]"
                class="flex flex-col items-center justify-center py-2 hover:bg-black hover:bg-opacity-5"
                @click="handleRoomPrice(room)"
              >
                <p class="font-bold">{{ room.sellPrice || '无房价' }}</p>
                <div
                  :class="[
                    getDateState(room.saleDate) ? 'opacity-20' : 'opacity-80',
                  ]"
                  class="flex items-center"
                >
                  <MdiMeals2 class="mr-1 opacity-80" />
                  <span>{{ room.breakfastNum || 0 }}</span>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div class="pb-20"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.room-list-top:hover .room-info,
.room-list-top:hover ul {
  background: hsl(var(--primary) / 8%);
}

.bg-main {
  background: hsl(var(--primary) / 20%);
}

.text {
  color: hsl(var(--card-foreground));
}

.no-select {
  user-select: none;
}

.leftBut::after {
  position: absolute;
  top: 50%;
  right: 0;
  display: block;
  width: 1px;
  height: 38px;
  content: '';
  background: #e7e8ec;
  transform: translateY(-50%);
}

.rightBut::after {
  position: absolute;
  top: 50%;
  left: 0;
  display: block;
  width: 1px;
  height: 38px;
  content: '';
  background: #e7e8ec;
  transform: translateY(-50%);
}
</style>
